package com.steven.ourcontest.contest.viewmodel

import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import com.steven.ourcontest.base.BaseViewModel
import com.steven.ourcontest.collect.api.CollectApi
import com.steven.ourcontest.contest.api.ContestApi
import com.steven.ourcontest.contest.bean.MatchInfoRes
import com.steven.ourcontest.team.api.TeamApi
import com.steven.ourcontest.team.bean.TeamInfoRes
import com.steven.ourcontest.utils.plusAssign

class MatchDetailViewModel : BaseViewModel() {

    private val _matchRes = MutableLiveData<MatchInfoRes?>()
    val matchRes: LiveData<MatchInfoRes?>
        get() = _matchRes

    private val _teamRes = MutableLiveData<TeamInfoRes?>()
    val teamRes: LiveData<TeamInfoRes?>
        get() = _teamRes

    fun queryMatchDetail(id: Long) {
        disposed += ContestApi.instance.searchMatchDetailById(id)
            .subscribe({
                _matchRes.value = it
            }, {
                _matchRes.value = null
                it.printStackTrace()
            })
    }

    fun searchTeamByMatch(matchId: Long) {
        disposed += ContestApi.instance.searchTeamByMatch(matchId)
            .subscribe({
                _teamRes.value = it
            }, {
                _teamRes.value = null
                it.printStackTrace()
            })
    }

    fun applyToTeam(teamId: Long, success: () -> Unit, error: (msg:String) -> Unit) {
        disposed += TeamApi.instance.applyToTeam(teamId)
            .subscribe({
                success.invoke()
            }, {
                it.message?.let { it1 -> error.invoke(it1) }
                it.printStackTrace()
            })
    }

    fun addHistory(matchId: Long){
        disposed += ContestApi.instance.addHistory(matchId)
            .subscribe({
            }, {
                it.printStackTrace()
            })
    }

    fun addMatchCollection(matchId: Long, success: () -> Unit) {
        disposed += CollectApi.instance.addMatchCollection(matchId)
            .subscribe({
                success.invoke()
            }, {
                it.printStackTrace()
            })
    }

    private var deleting = false
    fun deleteMatchCollection(matchId: Long, success: () -> Unit) {
        if (deleting)
            return
        deleting = true
        disposed += CollectApi.instance.deleteMatchCollection(matchId)
            .subscribe({
                deleting = false
                success.invoke()
            }, {
                deleting = false
                it.printStackTrace()
            })
    }
}